package com.lion.appletrip;

import com.alipay.sdk.app.PayTask;
import com.lion.appletrip.utils.PayResult;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class WebActivity extends Activity
{
	private static final int SDK_PAY_FLAG = 1;
	private WebView mWebView;
	private View ivLoading;
	private View btnPay;


	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_web);
		mWebView = (WebView)findViewById(R.id.webView_webActivity);
		ivLoading = findViewById(R.id.iv_loading);
		btnPay = findViewById(R.id.iv_pay_webview);
		Animation animation = AnimationUtils.loadAnimation(this, R.anim.loading);
		ivLoading.setAnimation(animation);
		Intent intent = getIntent();
		String html = intent.getStringExtra("html");
		WebSettings settings = mWebView.getSettings();
		settings.setDomStorageEnabled(true);
		settings.setJavaScriptEnabled(true);
		settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
		mWebView.loadUrl(html);
		mWebView.setOnKeyListener(new OnKeyListener()
		{

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event)
			{
				if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack())
				{
					mWebView.goBack();
					return true;
				}
				return false;
			}
		});
	
		mWebView.setWebViewClient(new WebViewClient()
		{

			@Override
			public void onReceivedError(WebView view, int errorCode,
			        String description, String failingUrl)
			{
				// super.onReceivedError(view, errorCode, description,
				// failingUrl);

			}

			public boolean shouldOverrideUrlLoading(WebView view, String url)
			{
				if (url != null && url.startsWith("tel:"))
				{
					Intent intent = new Intent(Intent.ACTION_VIEW, Uri
					        .parse(url));
					startActivity(intent);
					return true;
				}
				view.loadUrl(url);

				return true;
			}

			@Override
			public void onPageFinished(WebView view, String url)
			{
				ivLoading.clearAnimation();
				ivLoading.setVisibility(View.GONE);
				mWebView.setVisibility(View.VISIBLE);
				btnPay.setVisibility(View.VISIBLE);
				super.onPageFinished(view, url);
			}

			@Override
			public void onReceivedError(WebView view,
			        WebResourceRequest request, WebResourceError error)
			{
				view.loadDataWithBaseURL(null, "加载失败...", "text/html", "UTF-8",null);
			
				ivLoading.setVisibility(View.GONE);
				super.onReceivedError(view, request, error);
			}
		});
		findViewById(R.id.btn_back_webview).setOnClickListener(new OnClickListener()
		{
			
			@Override
			public void onClick(View v)
			{
				finish();
			}
		});
		btnPay.setOnClickListener(new OnClickListener()
		{
			
			@Override
			public void onClick(View v)
			{
				// 实际的代码
//				String url = "http://www.xxx.com/getOrderInfo";
//				Map<String, String> params = new HashMap<String, String>();
//				params.put("subject", "测试的商品");
//				params.put("body", "该测试商品的详细描述");
//				params.put("price", "0.01");
//				HTTPUtils.get(this, url, params, new VolleyListener() {
//					@Override
//					public void onResponse(final String arg0) {
//						alipay(arg0);
//					}
		//
//					@Override
//					public void onErrorResponse(VolleyError arg0) {
//					}
//				});
				// 测试代码
				final String payInfo = "partner=\"2088101568358171\"&seller_id=\"xxx@alipay.com\"&out_trade_no=\"0819145412-6177\"&subject=\"测试\"&body=\"测试测试\"&total_fee=\"0.01\"&notify_url=\"http://notify.msp.hk/notify.htm\"&service=\"mobile.securitypay.pay\"&payment_type=\"1\"&_input_charset=\"utf-8\"&it_b_pay=\"30m\"&sign=\"lBBK%2F0w5LOajrMrji7DUgEqNjIhQbidR13GovA5r3TgIbNqv231yC1NksLdw%2Ba3JnfHXoXuet6XNNHtn7VE%2BeCoRO1O%2BR1KugLrQEZMtG5jmJIe2pbjm%2F3kb%2FuGkpG%2BwYQYI51%2BhA3YBbvZHVQBYveBqK%2Bh8mUyb7GM1HxWs9k4%3D\"&sign_type=\"RSA\"";
				alipay(payInfo);
			}
		});
	}
	private void alipay(final String arg0) {
		// 必须异步调用
		new Thread() {
			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask(WebActivity.this);
				// 调用支付接口，获取支付结果
				String result = alipay.pay(arg0, true);

				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		}.start();
	}

	private Handler mHandler = new Handler() {
		@SuppressWarnings("unused")
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SDK_PAY_FLAG: {
				PayResult payResult = new PayResult((String) msg.obj);
				/**
				 * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
				 * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
				 * docType=1) 建议商户依赖异步通知
				 */
				String resultInfo = payResult.getResult();// 同步返回需要验证的信息

				String resultStatus = payResult.getResultStatus();
				// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
				if (TextUtils.equals(resultStatus, "9000")) {
					Toast.makeText(WebActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
				} else {
					// 判断resultStatus 为非"9000"则代表可能支付失败
					// "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
					if (TextUtils.equals(resultStatus, "8000")) {
						Toast.makeText(WebActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();

					} else {
						// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
						Toast.makeText(WebActivity.this, "支付失败", Toast.LENGTH_SHORT).show();

					}
				}
				break;
			}
			default:
				break;
			}
		};
	};

}
